import time
import subprocess
import os, sys 

SPLIT_ITEM = "|split|"

# 将 \\ 变为 /
def correct_file_spitter(fn:str):
    fn = fn.replace("\\", "/").replace("//", "/")
    return fn

# 获取视频路径列表 递归
def get_video_file_list(dir_path):
    names = os.listdir(dir_path)
    names = [os.path.join(dir_path, name) for name in names  ]
    names = [ correct_file_spitter(n) for n in names  ]
    res = []
    for p in names:
        if os.path.isdir(p):
            res.extend(get_video_file_list(p))
        else:
            if p.endswith(".mp4"):
                res.append(p)
    return res


# 获取 每个视频的时间
def get_video_duration_1(filename):
    start = time.time()
    result = subprocess.run(["ffprobe", "-v", "error", "-show_entries",
                             "format=duration", "-of",
                             "default=noprint_wrappers=1:nokey=1", filename],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    end = time.time()
    spend = end - start
    print("获取视频时长方法1耗时：", spend)
    return float(result.stdout)

def scan(OutFile , scan_dir ):
    if os.path.exists(OutFile):
        print("是否要重新生成[y/N]:")
        i = input()
        if not( i=='y' or i=='Y'):
            sys.exit(0)

    with open(OutFile, 'w', encoding='utf-8') as f:
        res = get_video_file_list( scan_dir )
        print(res)
        for fn in res:
            vtime = get_video_duration_1(fn)
            f.write("{}{}{}\n".format(fn, SPLIT_ITEM, int(vtime) )  )


if __name__ == "__main__":
    # res = video_duration_1("C:/Users/hhq/Desktop/vids/VID20230605204932.mp4")
    # print(res)

    scan_dir = "F:/soft/DownKyi/Media"
    OutFile = "./video/video_time.txt" 
    scan(OutFile, scan_dir)
    

        
